/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * cadastroBairros.java
 *
 * Created on 29/09/2009, 21:31:36
 */

package cparc;

import com.mysql.jdbc.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Administrador
 */
public class cadastroBairros extends javax.swing.JInternalFrame {

   boolean alterar = false;
   boolean cadastrar = false;
    /** Creates new form cadastroBairros */
    public cadastroBairros() {
        initComponents();
        tfCodBai.disable();
        tfNomBai.disable();

       DefaultTableModel modelo = (DefaultTableModel) tbBai.getModel();
        String search = "select bcod, bnom from cparc.cad_bai" ;
        Statement stm = null;
        int i =0;
            System.out.print(search);
        try  {
                stm = (Statement) conexao.getConnection(true).createStatement();
                ResultSet rs = stm.executeQuery(search);
                rs.afterLast();
                while(rs.previous()){
                    modelo.addRow(new String[] {Integer.toString(rs.getInt("bcod")), rs.getString("bnom")});
                    modelo.fireTableCellUpdated(i, 1);
                    modelo.fireTableCellUpdated(i, 2);
                    i++;
                     tfConsulta.requestFocusInWindow();
                    tfConsulta.selectAll();
                }
             
        }catch(Exception e){
               e.printStackTrace();
        }

       

  }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbBai = new javax.swing.JTable();
        tfConsulta = new java.awt.TextField();
        btConsultar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        tfCodBai = new java.awt.TextField();
        tfNomBai = new java.awt.TextField();
        label1 = new java.awt.Label();
        label2 = new java.awt.Label();
        SalBai = new javax.swing.JButton();
        AltBai = new javax.swing.JButton();
        CadBai = new javax.swing.JButton();
        ExcBai = new javax.swing.JButton();

        setClosable(true);
        setTitle("Cadastro de Bairros");
        setRequestFocusEnabled(false);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        tbBai.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código do Bairro", "Nome do Bairro"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbBai.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbBaiMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbBai);

        tfConsulta.setText("Digite o Nome do Bairro");
        tfConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfConsultaKeyPressed(evt);
            }
        });

        btConsultar.setText("Consultar");
        btConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConsultarActionPerformed(evt);
            }
        });
        btConsultar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btConsultarKeyPressed(evt);
            }
        });

        label1.setText("Código do Bairro");

        label2.setText("Nome do Bairro");

        SalBai.setText("Salvar");
        SalBai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SalBaiActionPerformed(evt);
            }
        });

        AltBai.setText("Alterar");
        AltBai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AltBaiActionPerformed(evt);
            }
        });

        CadBai.setText("Cadastrar");
        CadBai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CadBaiActionPerformed(evt);
            }
        });

        ExcBai.setText("Excluir");
        ExcBai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExcBaiActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(45, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(107, 107, 107)
                        .addComponent(tfCodBai, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(107, 107, 107)
                        .addComponent(tfNomBai, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(108, 108, 108))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(84, 84, 84)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(SalBai, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(AltBai)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(CadBai)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ExcBai)))
                        .addGap(42, 42, 42)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addComponent(tfConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btConsultar, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(tfCodBai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfNomBai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AltBai)
                    .addComponent(CadBai)
                    .addComponent(ExcBai))
                .addGap(18, 18, 18)
                .addComponent(SalBai)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tfConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btConsultar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(71, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void SalBaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalBaiActionPerformed
        if(cadastrar){
        String inserir = "insert into cparc.cad_bai values(" +  tfCodBai.getText() + "," + "'" + tfNomBai.getText()+ "'" + ")" ;

          try  {
            Statement stm = (Statement) conexao.getConnection(true).createStatement();
             stm.executeUpdate(inserir);

        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }
      }
        if (alterar){
            Statement stm = null;
            String cadastrar = "update cparc.cad_bai set bnom = \"" + tfNomBai.getText()+ "\" where bcod = " + tfCodBai.getText();


            try  {
            stm = (Statement) conexao.getConnection(true).createStatement();
            stm.executeUpdate(cadastrar);
            }
            catch(Exception e){
                String status = e.getMessage();
                System.out.println(status);
            }
        }
            tfNomBai.disable();
            tfCodBai.disable();
            tfNomBai.setVisible(false);
            tfNomBai.setVisible(true);
            tfCodBai.setVisible(false);
            tfCodBai.setVisible(true);
            tfConsulta.setText("");
            btConsultar.doClick();
            alterar = false;
            cadastrar = false;
            tfCodBai.setText("");
            tfNomBai.setText("");
            

    }//GEN-LAST:event_SalBaiActionPerformed

    private void CadBaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CadBaiActionPerformed
        tfCodBai.disable();
        tfNomBai.enable();
        String search = "select bcod from cparc.cad_bai" ;
        Statement stm = null;
        int codb = 0;
            System.out.print(search);
        try  {
                stm = (Statement) conexao.getConnection(true).createStatement();
                ResultSet rs = stm.executeQuery(search);
                System.out.print("deu certo");
                while(rs.next()){
            int cod = Integer.parseInt(rs.getString("bcod"));
            if (cod > codb)
                codb = cod;
        }
        }catch(Exception e){
               e.printStackTrace();
        }
        tfCodBai.setText(String.valueOf(codb + 1));
        tfNomBai.setText("");
        tfNomBai.requestFocusInWindow();
        cadastrar = true;
        alterar = false;
    }//GEN-LAST:event_CadBaiActionPerformed

    private void AltBaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AltBaiActionPerformed
       if (tfCodBai.getText().equals("") && tfNomBai.getText().equals("")){
        tfConsulta.setText("Digite o bairro para consultar...");
        tfConsulta.requestFocusInWindow();
        tfConsulta.selectAll();
       }else{
           tfNomBai.enable();
           tfNomBai.requestFocusInWindow();
           tfNomBai.selectAll();
       }
        alterar = true;
        cadastrar = false;
    }//GEN-LAST:event_AltBaiActionPerformed

    private void ExcBaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExcBaiActionPerformed
        Statement stm = null;
        String excluir = "delete from cparc.cad_bai where bcod = " + tfCodBai.getText();
        int n;

       Object[] options = { "Confirmar", "Cancelar" };
       n = JOptionPane.showOptionDialog(null, "Você está prestes a excluir a raça: " + tfNomBai.getText() + "!\n Realizar a exclusão?", "Operação de exclusão!", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
       System.out.println(String.valueOf(n));

       if(n == 0)
       {
       try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        stm.executeUpdate(excluir);
        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }
       }
       tfConsulta.setText("");
       btConsultar.doClick();
       tfCodBai.setText("");
       tfNomBai.setText("");
    }//GEN-LAST:event_ExcBaiActionPerformed

    private void btConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConsultarActionPerformed
      DefaultTableModel modelo = (DefaultTableModel) tbBai.getModel();
        modelo.setRowCount(0);
        Statement stm = null;
        String search = "select bcod, bnom from cparc.cad_bai where bnom like \"%" +tfConsulta.getText() + "%\"" ;
        int i=0;

        try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        ResultSet rs = stm.executeQuery(search);
        rs.afterLast();
        while(rs.previous()){
        modelo.addRow(new String[] {Integer.toString(rs.getInt("bcod")), rs.getString("bnom")});
        modelo.fireTableCellUpdated(i, 0);
        modelo.fireTableCellUpdated(i, 1);
        i++;
        }

        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }
    }//GEN-LAST:event_btConsultarActionPerformed

    private void tbBaiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbBaiMouseClicked
        int line = tbBai.getSelectedRow();
        String cod = (String) tbBai.getValueAt(line, 0);
        tfCodBai.setText(cod);
        String nom = (String) tbBai.getValueAt(line, 1);
        tfNomBai.setText(nom);

        if(alterar)
        {
        tfNomBai.enable();
        tfNomBai.requestFocusInWindow();
        tfNomBai.selectAll();
        }
    }//GEN-LAST:event_tbBaiMouseClicked

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_formKeyPressed

    private void btConsultarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btConsultarKeyPressed
      
    }//GEN-LAST:event_btConsultarKeyPressed

    private void tfConsultaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConsultaKeyPressed

        if(evt.getKeyCode()== 10)
        {
            btConsultar.doClick();

            tfConsulta.requestFocusInWindow();
            tfConsulta.selectAll();
        }
    }//GEN-LAST:event_tfConsultaKeyPressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AltBai;
    private javax.swing.JButton CadBai;
    private javax.swing.JButton ExcBai;
    private javax.swing.JButton SalBai;
    private javax.swing.JButton btConsultar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private java.awt.Label label1;
    private java.awt.Label label2;
    private javax.swing.JTable tbBai;
    private java.awt.TextField tfCodBai;
    private java.awt.TextField tfConsulta;
    private java.awt.TextField tfNomBai;
    // End of variables declaration//GEN-END:variables

}
